package cn.com.nes.site.service.app.impl;


import cn.com.nes.common.util.*;
import cn.com.nes.mybatis.agent.ope.mapper.IsAppMapper;
import cn.com.nes.mybatis.ctce.entity.WxUserSms;
import cn.com.nes.mybatis.integrateServ.entity.AppUser;
import cn.com.nes.mybatis.integrateServ.mapper.AppUserMapper;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.mtpf.MtpfToken;
import cn.com.nes.site.entity.sms.VerCodeReq;
import cn.com.nes.site.service.app.AppUserService;
import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedHashMap;


@Service
public class AppUserServiceImpl implements AppUserService {
    @Resource
    private AppUserMapper appUserMapper;

    @Resource
    private IsAppMapper isAppMapper;

    @Override
    public void insertAppSmsCode(VerCodeReq sms) {
        appUserMapper.insertAppSmsCode(sms.getPhone(), sms.getVercode(), sms.getSmstype());
    }

    @Override
    public PageData appUserReg(AppUser appUser) {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("Error!");
        String phone = appUser.getPhone();
        String verCode = appUser.getVerCode();
        String passWord ="";
        if("".equals( appUser.getPassWord()) ||  appUser.getPassWord()==null){
            passWord ="12345";
        }else{
            passWord=appUser.getPassWord();
        }
        String nickName = appUser.getNickName();
        if (StringUtils.isEmpty(phone)) {
            res.setRetCode(9);
            res.setRetMessage("手机号不能为空！");
            return res;
        }
        if (StringUtils.isEmpty(nickName)) {
            nickName = phone;
        }
        //来源于注册
      if (StringUtils.isEmpty(verCode)) {
            res.setRetCode(9);
            res.setRetMessage("验证码不能为空！");
            return res;
        }
        WxUserSms wxUserSms = appUserMapper.appUsercheckVerCodeIncreaseTime(phone, verCode);
        if (ObjectUtil.isNotNull(wxUserSms) && !"".equals(wxUserSms)) {
            if (wxUserSms.getSeconds() > wxUserSms.getPeriod()) {
                res.setRetCode(9);
                res.setRetMessage("验证码过期,请重新获取!");
                return res;
            }
            if (StringUtils.isEmpty(passWord)) {
                passWord = phone + "001,00";
            }

            // 厂商系统注册,如不註冊无法发送指令
            String mfepPwd = phone + "001,00";
            String md5Password = DesEncryptorUtil.encrypt(mfepPwd);
            String sjly = "qgApp";
            //創建厂家用户、先刪除再添加
            AppUser manufacturerUser = new AppUser();
            manufacturerUser.setPassWord(md5Password);
            manufacturerUser.setId("qgApp" + phone);
            manufacturerUser.setPhone("qgApp" + phone);
            manufacturerUser.setSex("男");
            manufacturerUser.setSfsc("0");
            manufacturerUser.setSjly("0");
            isAppMapper.deleteManufacturerUser(manufacturerUser.getPhone());
            isAppMapper.addManufacturerUser(manufacturerUser);
            LinkedHashMap<String, Object> e = new LinkedHashMap<String, Object>();
            e.put("mm", mfepPwd);
            e.put("loginType", 1);
            e.put("phone", "qgApp" + phone);
            e.put("type", 1);
            String mfepuser = JsonUtil.getStriFromObj(e);
            appUser.setMfepuser(mfepuser);
            appUser.setSjly(sjly);
            appUser.setNickName(nickName);
            appUser.setPhone(phone);
            appUser.setId(phone);
            appUser.setPassWord(passWord);
            appUserMapper.insertWxUsers(appUser);
            res.setRetCode(0);
            res.setRetMessage("OK");
       } else {
            res.setRetCode(9);
            res.setRetMessage("验证码错误，请重新输入!");
        }
        return res;
    }

    @Override
    public PageData appUsercheckVerCodeIncreaseTime(String phone, String code) {
        WxUserSms wxUserSms = appUserMapper.appUsercheckVerCodeIncreaseTime(phone, code);
        if (ObjectUtil.isNotNull(wxUserSms) && !"".equals(wxUserSms)) {
            if (wxUserSms.getSeconds() > 60 * 30) {
                return PageData.error("验证码过期,请重新获取!");
            } else {
                return PageData.ok();
            }

        }
        return PageData.error("验证码不正确！");
    }

    @Override
    public boolean checkUser(DataReq req) {
        AppUser appUser = appUserMapper.checkUser((String) req.getReqData().get("phone"), null);
        if (ObjectUtil.isNotNull(appUser) && !"".equals(appUser)) {
            if (Integer.valueOf(appUser.getPhone()) > 0) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    @Override
    public PageData login(AppUser appUser) throws Exception {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("登录失败！");
        JwtUtil jwtUtil = new JwtUtil();
        String verCode =  appUser.getVerCode();
        String phone = appUser.getPhone();
        String passWord = appUser.getPassWord();
            if (StringUtils.isEmpty(phone)) {
                res.setRetCode(9);
                res.setRetMessage("请输入手机号！");
                return res;
            }

        AppUser checkAppUser = null;
        if (StringUtils.isEmpty(verCode)) {
            res.setRetCode(9);
            res.setRetMessage("验证码不能为空！");
            return res;
        }
    WxUserSms wxUserSms = appUserMapper.appUsercheckVerCodeIncreaseTime(phone, verCode);
        if (ObjectUtil.isNotNull(wxUserSms) && !"".equals(wxUserSms)) {
            if (wxUserSms.getSeconds() > wxUserSms.getPeriod()) {
                res.setRetCode(9);
                res.setRetMessage("验证码过期,请重新获取!");
                return res;
            }

        }else{
            res.setRetCode(9);
            res.setRetMessage("验证码错误，请重新输入!");
            return res;
        }
        if (StringUtils.isEmpty(passWord)) {
            checkAppUser = appUserMapper.checkUser(appUser.getPhone(), null);
            if (ObjectUtil.isNotNull(checkAppUser) && !"".equals(checkAppUser)) {
                res.setData(BeanUtils.describe(checkAppUser));
                res.setRetCode(0);
                res.setRetMessage("OK");

            } else {
                res.setRetCode(9);
                res.setRetMessage("输入的手机号不正确！");
                return res;
            }
        } else {
            checkAppUser = appUserMapper.checkUserPassWord(phone, passWord);
            if (ObjectUtil.isNotNull(checkAppUser) && !"".equals(checkAppUser)) {
                res.setData(BeanUtils.describe(checkAppUser));
                res.setRetCode(0);
                res.setRetMessage("OK");
            } else {
                res.setRetCode(9);
                res.setRetMessage("用户名或密码不正确！");
                return res;
            }
        }
        String mfepuser = checkAppUser.getMfepuser();
        String tmpStr = "";
        if (org.apache.commons.lang.StringUtils.isEmpty(mfepuser)) {
            tmpStr = HttpUtils.submitDataByDoPostJson(Globals.MTPF_LOGINUSER, Globals.MTPF_LOGINURL);
        } else {
            tmpStr = HttpUtils.submitDataByDoPostJson(mfepuser, Globals.MTPF_LOGINURL_APP);
        }
        MtpfToken mtpftoken = (MtpfToken) JsonUtil.getObjFromStr(tmpStr, MtpfToken.class);
        if (mtpftoken != null && mtpftoken.getRetCode() == 0) {
            String token = mtpftoken.getPage().get(0).getToken();
            res.getData().put("mfep_token", token);
        }
        // 生成jwt信息
        String str = JsonUtil.getStriFromObj(checkAppUser);
        String s = jwtUtil.createJWT(checkAppUser.getUserId() + "", str, Globals.TOKEN_TIME);
        res.getData().put("key", s);
        return res;
    }

    @Override
    public PageData updatePassword(AppUser appUser) {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("Error!");
        String oldpwd = appUser.getOldpwd();
        String newpwd =appUser.getNewpwd();
        AppUser queryUser= appUserMapper.queryUserPassWord(appUser.getUserId(),oldpwd);
        if (ObjectUtil.isNull(queryUser) && "".equals(queryUser)) {
                res.setRetCode(9);
                res.setRetMessage("原密码不正确，请重新输入！");
                return res;
        }
        appUserMapper.updateUserPassWord(appUser.getUserId(),newpwd);
            res.setRetCode(0);
            res.setRetMessage("OK");
            return res;
        }
        @Override
        public PageData getUserMesg (AppUser appUser){
            PageData res = new PageData();
            res.setRetCode(9);
            res.setRetMessage("Error!");
            AppUser appUserData   = appUserMapper.queryUser(appUser);
            if (ObjectUtil.isNull(appUserData) && "".equals(appUserData)) {
                res.setRetCode(0);
                res.setRetMessage("OK");
            }
            return res;
        }
}